import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';
import { t } from '@lingui/macro';

export default class OtherStationStore {
  _args = {
    search: {},
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };
  total = 0;
  data = [];
  operatingCompanys = [];
  operationCompany = [];
  platformCompany = [];
  loading = false;
  _region = {};

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  get api() {
    return api;
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    const { result = '', fullId = '' } = this._region;
    search.cityName = result;
    if (fullId.split(':').length === 2) {
      search.areaName = fullId.split(':')[1];
      search.cityName = fullId.split(':')[0];
    }
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count({ search });
      const prices = yield api.search({ search, pg });
      const getThirdPrices = yield Promise.all(prices.map(async (p) => {
        const res = await api.getStationThird(p.stationId);
        return { ...p, third: res };
      }));
      this.data = getThirdPrices;
    } finally {
      this.loading = false;
    }
  }

  * update(data) {
    yield api.update({ ...data });
    yield this._reload(data);
  }

  * remove(id) {
    yield api.remove(id);
    yield this._reload();
  }

  * getCompany(args) {
    const res = yield api.getCompany(args);
    const toggleCompanys = res.map((p) => ({ label: p.name, value: p.id }));
    return toggleCompanys;
  }

  * getCity(args) {
    const res = yield api.getDictsItemTop(args);
    const regions = res.map((p) => ({ label: p.name, value: p.itemId }));
    return regions;
  }

  * getStationThird(id) {
    return yield api.getStationThird(id);
  }

  * create(station) {
    yield api.create(station);
    yield this._reload(station);
  }

  * updateAllStation() {
    yield api.updateAllStation();
    yield this.query();
  }

  get region() {
    return this._region;
  }

  set region(r) {
    this._region = r;
    this.query();
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  * _reload() {
    yield this.query();
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
    // _.mergeWith(this._args.pg, pg, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }
}
